package com.aispeech.detector.utils;

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class AudioFileWrite {

    private final static String TAG = "AudioFileWrite";
    private String on_buf_file_name;

    private File audioFile;
    private BufferedOutputStream bosRec;

    public AudioFileWrite(Application appContext) {
        Log.d(TAG, "AudioFileWrite: ");
        try {
            on_buf_file_name = appContext.getExternalCacheDir().getAbsolutePath() + File.separator + "readbuf.pcm";
        } catch (Exception e) {
            e.printStackTrace();
            on_buf_file_name = "/sdcard/aispeech/onBuf.pcm";
        }
    }

    public void startWrite(String filePath) {
        try {
            this.audioFile = new File(TextUtils.isEmpty(filePath) ? on_buf_file_name : filePath);
            File fileParent = audioFile.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }

            this.bosRec = new BufferedOutputStream(new FileOutputStream(audioFile));
            Log.d(TAG, "startWrite: patch = " + audioFile.getAbsolutePath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void writeBuffer(byte[] audioBuf) {
        try {
            if (null != bosRec && null != audioBuf && audioBuf.length > 0) {
                bosRec.write(audioBuf, 0, audioBuf.length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized void closeWrite() {
        Log.d(TAG, "closeWrite: ");
        try {
            if (null != bosRec) {
                this.bosRec.flush();
                this.bosRec.close();
                this.bosRec = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
